package tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * 先从根节点开始，把左子树节点全都压栈，再一个个弹栈，让右子节点进栈
 */
public class Inorder_94 {
    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }

        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        while (root != null || !stack.isEmpty()) {
            // 先把根节点和左子树节点先压栈
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.right != null) {
                // 不能直接在这里向栈里压入节点，否则会在while循环中重复压栈
                // stack.push(node.right);
                root = node.right;
            }
        }

        return list;
    }
}
